#coding=utf-8
#auth:beck shen
#date:2017-11-13


from pytw._globals.config import GlobalsConfig

import os
import functools
from datetime import datetime, timedelta
from collections import namedtuple

from twisted.python import log as _log, logfile as _logfile


class Log(object):

    """
    重写日志文件系统,更改为开关控制日志
    """

    __logs__ = {} 

    @classmethod
    def _log_path(cls, name):
        """
        创建日志文件目录
        """
        #从全局配置获取日志文件路径
        new = GlobalsConfig.GLOBAL_DEFAULT_LOG_PATH
        if not os.path.exists(new):
            os.makedirs(new)
        return new 

    @classmethod
    def create(cls, name, publisher = None):
        """
        创建新的日志文件对象
        """
        obj = cls.__logs__.get(name, None)
        if obj is not None:
            return obj
        #日志文件路径
        path = cls._log_path(name)
        #日志文件名
        filename = '%s.log'%(name)
        if not publisher:
            publisher = _log.LogPublisher()
        observer = _log.FileLogObserver(_logfile.DailyLogFile(filename, path)).emit
        #全局日志对象
        if publisher is _log.theLogPublisher:
            _log.startLoggingWithObserver(observer)
        else:
            publisher.addObserver(observer)
        #控制日志开关
        obj = namedtuple('LogWrap', ['publisher', 'status'])
        _obj = obj._make([publisher, 1])
        cls.__logs__[name] = _obj
        return _obj

    @classmethod
    def clear(cls):
        """
        清理过期的日志文件
        """
        days = GlobalsConfig.GLOBAL_DEFAULT_LOG_DAYS
        delete_date = datetime.now() - timedelta(days = days)
        for name in cls.__logs__.keys():
            cls._delete_logfile(name, delete_date)   
 
    @classmethod
    def _delete_logfile(cls, name, d):
        """
        删除数据文件
        """
        delete_file = os.path.join(
            cls._log_path(name),'%s.log.%s'%(name,
            '_'.join((str(d.year), str(d.month), str(d.day))))
        )
        try:
            os.remove(delete_file)
            info("delete_log_file===>:", delete_file)
        except:
            pass 
        
    @classmethod
    def close_open(cls, status, name):
        """
        关闭某种日志输出
        """
        obj = cls.__logs__.get(name, None)
        if not obj:
            return
        obj.status = status

    @classmethod
    def log_(cls, name, *args, **kwargs):
        """
        日志按名称分文件输出
        """
        obj = cls.create(name)
        if obj.status == 0:
            return
        obj.publisher.msg(*args, **kwargs)
 

#默认开启twisted自带日志，将标准输入重定向
Log.create('twisted', _log.theLogPublisher)
msg = _log.msg

#应用错误日志
err = functools.partial(Log.log_, 'err')
#应用info日志
info = functools.partial(Log.log_, 'info')
#应用警告日志
warn = functools.partial(Log.log_, 'warn')
#应用调试日志
debug = functools.partial(Log.log_, 'debug')
#数据sql语句日志
sql = functools.partial(Log.log_, 'sql')

#关闭日志close_log('info')
close_log = functools.partial(Log.close_open, 0)
#打开日志open_log('info')
open_log = functools.partial(Log.close_open, 1)
